'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { signUp } from '@/lib/auth-client';
import { useToast } from '@/components/ui/ToastProvider';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import { Eye, EyeOff, Mail, Lock, User, ArrowRight, Check } from 'lucide-react';

export default function RegisterPage() {
  const router = useRouter();
  const { showSuccess, showError } = useToast();
  
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
    confirmPassword: '',
  });
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false);

  // 密码强度检查
  const getPasswordStrength = (password: string) => {
    let strength = 0;
    const checks = {
      length: password.length >= 8,
      lowercase: /[a-z]/.test(password),
      uppercase: /[A-Z]/.test(password),
      numbers: /\d/.test(password),
      special: /[!@#$%^&*(),.?":{}|<>]/.test(password),
    };
    
    Object.values(checks).forEach(check => {
      if (check) strength++;
    });
    
    return { strength, checks };
  };

  const passwordAnalysis = getPasswordStrength(formData.password);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!agreedToTerms) {
      showError('注册失败', '请同意服务条款和隐私政策');
      return;
    }

    if (formData.password !== formData.confirmPassword) {
      showError('注册失败', '两次输入的密码不一致');
      return;
    }

    if (passwordAnalysis.strength < 3) {
      showError('注册失败', '密码强度太弱，请设置更复杂的密码');
      return;
    }

    setLoading(true);

    try {
      const result = await signUp.email({
        name: formData.name,
        email: formData.email,
        password: formData.password,
      });

      if (result.error) {
        showError('注册失败', result.error.message || '注册过程中出现错误');
        return;
      }

      showSuccess('注册成功', '欢迎加入我们！正在跳转到您的仪表板...');
      
      // 获取用户ID并跳转到用户的dashboard页面
      if (result.data?.user?.id) {
        router.push(`/${result.data.user.id}/dashboard`);
      } else {
        // 如果没有获取到用户ID，跳转到首页
        router.push('/');
      }
    } catch (error: any) {
      console.error('注册失败:', error);
      showError('注册失败', error.message || '网络错误，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <div className="w-full">
      {/* 标题区域 */}
      <div className="text-center mb-8">
        <h2 className="text-3xl font-bold text-gray-900 mb-2">
          创建账户
        </h2>
        <p className="text-gray-600">
          加入我们，开启您的数字化旅程
        </p>
      </div>

      {/* 注册表单 */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 姓名输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            姓名
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <User className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              placeholder="输入您的姓名"
              required
            />
          </div>
        </div>

        {/* 邮箱输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            邮箱地址
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <Mail className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
              className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              placeholder="输入您的邮箱地址"
              required
            />
          </div>
        </div>

        {/* 密码输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            密码
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <Lock className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type={showPassword ? 'text' : 'password'}
              value={formData.password}
              onChange={(e) => handleInputChange('password', e.target.value)}
              className="block w-full pl-10 pr-12 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              placeholder="设置您的密码"
              required
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
            >
              {showPassword ? (
                <EyeOff className="h-5 w-5" />
              ) : (
                <Eye className="h-5 w-5" />
              )}
            </button>
          </div>
          
          {/* 密码强度指示器 */}
          {formData.password && (
            <div className="mt-2">
              <div className="flex space-x-1 mb-2">
                {[1, 2, 3, 4, 5].map((level) => (
                  <div
                    key={level}
                    className={`h-1 flex-1 rounded ${
                      level <= passwordAnalysis.strength
                        ? passwordAnalysis.strength <= 2
                          ? 'bg-red-500'
                          : passwordAnalysis.strength <= 3
                          ? 'bg-yellow-500'
                          : 'bg-green-500'
                        : 'bg-gray-200'
                    }`}
                  />
                ))}
              </div>
              <div className="text-xs space-y-1">
                {Object.entries(passwordAnalysis.checks).map(([key, passed]) => (
                  <div
                    key={key}
                    className={`flex items-center space-x-1 ${
                      passed ? 'text-green-600' : 'text-gray-400'
                    }`}
                  >
                    <Check className={`h-3 w-3 ${passed ? 'opacity-100' : 'opacity-30'}`} />
                    <span>
                      {key === 'length' && '至少8个字符'}
                      {key === 'lowercase' && '包含小写字母'}
                      {key === 'uppercase' && '包含大写字母'}
                      {key === 'numbers' && '包含数字'}
                      {key === 'special' && '包含特殊字符'}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* 确认密码输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            确认密码
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <Lock className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type={showConfirmPassword ? 'text' : 'password'}
              value={formData.confirmPassword}
              onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
              className={`block w-full pl-10 pr-12 py-3 border rounded-lg focus:outline-none focus:ring-2 transition-colors ${
                formData.confirmPassword && formData.password !== formData.confirmPassword
                  ? 'border-red-300 focus:ring-red-500 focus:border-red-500'
                  : 'border-gray-300 focus:ring-blue-500 focus:border-blue-500'
              }`}
              placeholder="再次输入密码"
              required
            />
            <button
              type="button"
              onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
            >
              {showConfirmPassword ? (
                <EyeOff className="h-5 w-5" />
              ) : (
                <Eye className="h-5 w-5" />
              )}
            </button>
          </div>
          {formData.confirmPassword && formData.password !== formData.confirmPassword && (
            <p className="mt-1 text-sm text-red-600">密码不一致</p>
          )}
        </div>

        {/* 服务条款同意 */}
        <div>
          <label className="flex items-start space-x-3">
            <input
              type="checkbox"
              checked={agreedToTerms}
              onChange={(e) => setAgreedToTerms(e.target.checked)}
              className="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <div className="text-sm text-gray-600 leading-relaxed">
              我已阅读并同意{' '}
              <Link href="/terms" className="text-blue-600 hover:text-blue-500 font-medium">
                服务条款
              </Link>
              {' '}和{' '}
              <Link href="/privacy" className="text-blue-600 hover:text-blue-500 font-medium">
                隐私政策
              </Link>
            </div>
          </label>
        </div>

        {/* 注册按钮 */}
        <button
          type="submit"
          disabled={loading || !agreedToTerms}
          className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center space-x-2"
        >
          {loading ? (
            <LoadingSpinner size="sm" text="" />
          ) : (
            <>
              <span>创建账户</span>
              <ArrowRight className="h-4 w-4" />
            </>
          )}
        </button>
      </form>

      {/* 登录链接 */}
      <div className="mt-8 text-center">
        <p className="text-gray-600">
          已有账户？{' '}
          <Link
            href="/auth/login"
            className="text-blue-600 hover:text-blue-500 font-medium"
          >
            立即登录
          </Link>
        </p>
      </div>
    </div>
  );
} 